(ns acst.utils.handle-exp
  (:require [clojure.string :refer [split]]))



(defn get-error [result]
  (:error (first result)))


(def ex-regex
  [[#"null value in column \"(\w+)\" violates not-null constraint" #(str % "不能为空")]
   [#"ERROR: duplicate key value violates unique constraint \"(\w+)\"" #(str (second (split % #"_")) "已存在")]
   [#"violates check constraint \"(\w+)\"" #(str % "限制未通过")]])

(defn format-pgsqlex [ex]
  (->> (let [message (.getMessage ex)]
         ((fn [msg iter]
            (if (= '() iter)
              message
              (let [result (re-find (first (first iter)) msg) handle-fn (second (first iter))]
                (if (nil? result)
                  (recur msg (rest iter))
                  (apply handle-fn (rest result)))))) message ex-regex))
       (hash-map :error)
       (vector)))

(defmacro handle-sqlex [body & msg]
  `(try ~body
        (catch Exception e#
          (or ~@msg (format-pgsqlex e#)))))